<template>
  <div class="base-container" id="main">
    <t-steps :current="activeForm" status="process" :onChange="onCurChanged">
      <t-step-item v-for="(item, index) in stepList" :title="item.title" :key="index" :content="isSubmit(item.id)">
      </t-step-item>
    </t-steps>
    <t-loading text="加载中..." :fullscreen="false" attach="#main" :loading="applyLoading" size="medium"> </t-loading>
    <!-- 基本信息 -->
    <t-form ref="form" :key="activeForm" v-if="activeForm === 0" class="step-form" :data="formData0" :rules="rules0"
      labelWidth="140px">
      <t-alert v-if="false" style="margin-bottom: 14px" theme="info" title="填写说明：">
        <div slot="message">
          <p class="span-txt">
            一、严格按照报表设定的格式如实填写，不得自行增删报表栏目（内部表格可自行扩充），字体统一采用小四号仿宋字体。
          </p>
          <p class="span-txt">
            二、“申报单位名称”需为法人单位名称，“申报科普站名称”是指申报单位内开展交通运输科普功能的场所，也可与“申报单位名称”相同（如博物馆、科技馆）。企业集团、高校及科研院所不得以单位名称作为申报科普站名称。
          </p>
          <p class="span-txt">
            三、报表采用A4复印纸双面打印装订，要求目录和页码标注清晰，另行提供的材料应与申报表一并装订。
          </p>
          <p class="span-txt">
            四、申报单位应对所提供材料的真实性负责，由单位负责人签字，加盖单位公章后报出（根据单位性质，通过地方交通运输主管部门推荐或直接申报）。
          </p>
          <p class="span-txt">
            五、各省（区、市）、新疆生产建设兵团交通运输厅（局、委）会同省（区、市）、新疆生产建设兵团科技厅（局、委）填写推荐单位意见，负责人签字，分别加盖交通运输厅（局、委）和科技厅（局、委）公章后报出；部管国家局、行业学（协）会、中央级企业集团作为推荐单位的，由推荐单位填写推荐意见，签字盖章后报出。
          </p>
        </div>
      </t-alert>
      <t-row style="align-items: stretch" :gutter="14">
        <t-col :span="6">
          <t-card class="step-card" size="small" title="基本信息">
            <t-form-item label="科普站名称：" name="name">
              <t-input clearable style="width: 390px" v-model="formData0.name"></t-input>
            </t-form-item>
            <t-form-item label="科普站地址：" name="address">
              <t-input clearable style="width: 390px" v-model="formData0.address"></t-input>
            </t-form-item>
            <t-form-item label="通讯地址：" name="communicateAddress">
              <t-input clearable style="width: 390px" v-model="formData0.communicateAddress"></t-input>
            </t-form-item>
            <t-form-item label="邮编：" name="postCode">
              <t-input clearable style="width: 390px" v-model="formData0.postCode"></t-input>
            </t-form-item>
            <t-form-item label="法定代表人：" name="legalPerson">
              <t-input clearable style="width: 390px" v-model="formData0.legalPerson"></t-input>
            </t-form-item>
            <!-- <t-form-item label="申报单位：" name="userDeptName">
              <t-input clearable style="width: 390px" disabled v-model="userDeptName"></t-input>
            </t-form-item> -->
            <t-form-item label="联系人：" name="linkerPerson">
              <t-input clearable style="width: 390px" v-model="formData0.linkerPerson"></t-input>
            </t-form-item>
            <t-form-item label="移动电话：" name="mobilePhone">
              <t-input clearable style="width: 390px" placeholder="请输入手机号码" v-model="formData0.mobilePhone"></t-input>
            </t-form-item>
            <t-form-item label="固定电话：" name="fixedPhone">
              <t-input clearable style="width: 390px" v-model="formData0.fixedPhone"></t-input>
            </t-form-item>
            <t-form-item label="传真：" name="fax">
              <t-input clearable style="width: 390px" v-model="formData0.fax"></t-input>
            </t-form-item>
            <t-form-item label="公共邮箱：" name="email">
              <t-input clearable style="width: 390px" v-model="formData0.email"></t-input>
            </t-form-item>
            <t-form-item label="基地类型：" name="baseType">
              <t-select v-model="formData0.baseType" clearable placeholder="请选择基地类型" :options="dict.type.base_type"
                style="width: 390px" />
            </t-form-item>
            <t-form-item label="交通运输科普工作管理制度、规划或计划 （3-5年内）：" name="workPlan" labelAlign="top">
              <t-radio-group v-model="formData0.workPlan">
                <t-radio value="1">有（请附书面材料）</t-radio>
                <t-radio value="0">无</t-radio>
              </t-radio-group>
            </t-form-item>
            <t-form-item v-if="formData0.workPlan === '1'" name="projectFileData">
              <div v-for="fileData in projectFileData" :key="fileData.id">
                <file-upload v-if="fileData.id == 2" v-model="fileData.fileIds" :moduleKey="fileData.moduleKey"
                  :fileList.sync="fileData.fileLists" :multiple="true">
                  <t-button variant="outline">
                    <t-icon name="cloud-upload" slot="icon" />
                    点击上传
                  </t-button>
                </file-upload>
              </div>
            </t-form-item>
          </t-card>
        </t-col>
        <t-col :span="6">
          <t-card class="step-card" size="small" title="交通运输科普展示场所">
            <t-alert style="margin-bottom: 10px" theme="info" message="科技场馆面积原则上应在100㎡以上"></t-alert>
            <t-form-item label="室内场馆面积：" name="indoorVenues">
              <t-input-adornment append="㎡">
                <t-input-number clearable style="width: calc(390px - 39px)" v-model="formData0.indoorVenues"
                  theme="normal" :min="0" />
              </t-input-adornment>
            </t-form-item>
            <t-form-item label="室外场馆面积：" name="outdoorVenues">
              <t-input-adornment append="㎡">
                <t-input-number clearable style="width: calc(390px - 39px)" v-model="formData0.outdoorVenues"
                  theme="normal" :min="0" />
              </t-input-adornment>
            </t-form-item>
            <t-form-item label="影视报告厅面积：" name="lectureHall">
              <t-input-adornment append="㎡">
                <t-input-number clearable style="width: calc(390px - 39px)" v-model="formData0.lectureHall"
                  theme="normal" :min="0" />
              </t-input-adornment>
            </t-form-item>
            <t-form-item label="每年对外开放时间：" name="openDays" help="具备常年开放条件的科技场馆，每年向公众开放的天数不少于200天">
              <t-input-adornment append="天">
                <t-input-number clearable style="width: calc(390px - 39px)" v-model="formData0.openDays" theme="normal"
                  :min="0" />
              </t-input-adornment>
            </t-form-item>
            <t-form-item label="每年接待公众：" name="receptionPerson" help="科技场馆年接待量原则上应在500人以上">
              <t-input-adornment append="人次">
                <t-input-number clearable style="width: calc(390px - 53px)" v-model="formData0.receptionPerson"
                  theme="normal" :min="0" />
              </t-input-adornment>
            </t-form-item>
          </t-card>
        </t-col>
      </t-row>
      <t-row style="align-items: stretch" :gutter="14">
        <t-col :span="6">
          <t-card class="step-card" size="small" title="交通运输科普经费年度投入情况">
            <t-form-item label="政府投资：" name="popularScienceFunding.governmentInvest">
              <t-input-adornment append="万元">
                <t-input-number clearable style="width: calc(390px - 53px)"
                  v-model="formData0.popularScienceFunding.governmentInvest" theme="normal" :min="0" />
              </t-input-adornment>
            </t-form-item>
            <t-form-item label="社会赞助：" name="popularScienceFunding.socialSponsorship">
              <t-input-adornment append="万元">
                <t-input-number clearable style="width: calc(390px - 53px)"
                  v-model="formData0.popularScienceFunding.socialSponsorship" theme="normal" :min="0" />
              </t-input-adornment>
            </t-form-item>
            <t-form-item label="单位自筹：" name="popularScienceFunding.unitSelf">
              <t-input-adornment append="万元">
                <t-input-number clearable style="width: calc(390px - 53px)"
                  v-model="formData0.popularScienceFunding.unitSelf" theme="normal" :min="0" />
              </t-input-adornment>
            </t-form-item>
            <t-form-item label="其他：" name="popularScienceFunding.other">
              <t-input-adornment append="万元">
                <t-input-number clearable style="width: calc(390px - 53px)"
                  v-model="formData0.popularScienceFunding.other" theme="normal" :min="0" />
              </t-input-adornment>
            </t-form-item>
          </t-card>
        </t-col>
        <t-col :span="6">
          <t-card class="step-card" size="small" title="基地对外宣传渠道">
            <t-form-item label="渠道类型：" name="popularScienceBaseChannel" labelAlign="top">

              <div style="display: flex;flex-direction: column;">
                <div style="display: flex;align-items: center;margin-top: 20px;">


                  <t-radio-group v-model="formData0.popularScienceBaseChannel.webSite">
                    <t-radio value="1" allow-uncheck>网站</t-radio>
                  </t-radio-group>

                  <t-radio-group v-model="formData0.popularScienceBaseChannel.web">
                    <t-radio value="1" allow-uncheck>网页</t-radio>
                  </t-radio-group>


                  <span>网址：</span>
                  <t-input clearable style="width: 300px" v-model="formData0.popularScienceBaseChannel.url"></t-input>
                </div>

                <div style="display: flex;align-items: center;margin-top: 20px;">
                  <t-radio-group v-model="formData0.popularScienceBaseChannel.webo">
                    <t-radio value="1" allow-uncheck>微博</t-radio>
                  </t-radio-group>
                  <t-radio-group v-model="formData0.popularScienceBaseChannel.weChat">
                    <t-radio value="1" allow-uncheck>微信</t-radio>
                  </t-radio-group>
                  <t-radio-group v-model="formData0.popularScienceBaseChannel.otherr">
                    <t-radio value="1" allow-uncheck>其他客户端</t-radio>
                  </t-radio-group>
                  <span>名称：</span>
                  <t-input clearable style="width: 300px"
                    v-model="formData0.popularScienceBaseChannel.otherClientName"></t-input>
                </div>
              </div>
            </t-form-item>


            <!-- <t-form-item label="渠道类型：" name="popularScienceBaseChannel.channelType" labelAlign="top">
              <t-radio-group name="city" v-model="formData0.popularScienceBaseChannel.channelType"
                :options="dict.type.channel_type" />
            </t-form-item>
            <div>
              <t-form-item v-if="['1', '2'].includes(formData0.popularScienceBaseChannel.channelType)" label="网址："
                name="popularScienceBaseChannel.url" key="channelType12">
                <t-input clearable style="width: 390px" v-model="formData0.popularScienceBaseChannel.url"></t-input>
              </t-form-item>
              <t-form-item v-if="['3', '4', '5'].includes(formData0.popularScienceBaseChannel.channelType)" label="名称："
                name="popularScienceBaseChannel.otherClientName" key="channelType5">
                <t-input clearable style="width: 390px"
                  v-model="formData0.popularScienceBaseChannel.otherClientName"></t-input>
              </t-form-item>
            </div> -->
          </t-card>
        </t-col>
      </t-row>
      <t-row>
        <t-card class="step-card" size="small" title="科普工作人员情况">
          <base-member ref="base-member" :edit-open="true" v-model="formData0.popularScienceWorkers"></base-member>
        </t-card>
      </t-row>

      <t-row>
        <t-col :span="11">
          <t-button theme="primary" @click="onSubmit0()">下一步</t-button>
        </t-col>
        <t-col :span="1" class="operation-container">
          <t-button variant="outline" @click="close">返回</t-button>
        </t-col>
      </t-row>
    </t-form>
    <!-- 总体概括 -->
    <t-form v-else-if="activeForm === 1" ref="form" :key="activeForm" class="step-form" labelAlign="top" :rules="rules1"
      :data="formData1" labelWidth="140px">
      <t-tag theme="danger" variant="light">*基地总体概况（包括申报单位简介、基地科普特色、基地创建历程、发展愿景等，不超过1000字）:</t-tag>
      <t-form-item name="survey">
        <tiny-mce-editor :key="activeForm" :height="650" :maxlength="1000" :textLength.sync="lengthLimitObj.survey"
          v-model="formData1.survey"></tiny-mce-editor>
      </t-form-item>
      <t-row>
        <t-col :span="11">
          <t-space :size="10">
            <t-button @click="onCurChanged(0)" theme="primary" variant="base">上一步</t-button>
            <t-button theme="primary" @click="onSubmit1">下一步</t-button>
          </t-space>
        </t-col>
        <t-col :span="1" class="operation-container">
          <t-button variant="outline" @click="close">返回</t-button>
        </t-col>
      </t-row>
    </t-form>
    <!-- 内容体系 -->
    <t-form v-else-if="activeForm === 2" ref="form" :key="activeForm" class="step-form" labelAlign="top"
      :data="formData2" :rules="rules2" labelWidth="140px">
      <t-tag theme="danger" variant="light">*交通运输科普展示内容体系（不超过1000字，要求层次清晰）:</t-tag>
      <t-form-item name="content">
        <tiny-mce-editor :key="activeForm" :height="650" :maxlength="1000" :textLength.sync="lengthLimitObj.content"
          v-model="formData2.content"></tiny-mce-editor>
      </t-form-item>
      <t-row>
        <t-col :span="11">
          <t-space :size="10">
            <t-button @click="onCurChanged(1)" theme="primary" variant="base">上一步</t-button>
            <t-button theme="primary" @click="onSubmit2">下一步</t-button>
          </t-space>
        </t-col>
        <t-col :span="1" class="operation-container">
          <t-button variant="outline" @click="close">返回</t-button>
        </t-col>
      </t-row>
    </t-form>
    <!-- 特色照片 -->
    <t-form v-else-if="activeForm === 3" ref="form" :key="activeForm" :data="formData3" class="step-form"
      labelAlign="top" :rules="rules3" labelWidth="140px">
      <t-tag theme="danger" variant="light">*列出展示基地交通运输科普特色照片一套（不超过10张），并在每张照片下面做简要说明（不超过50字）:</t-tag>
      <t-form-item :show-error-message="false" name="imageList">
        <base-image v-model="formData3.imageList" ref="base-image" :obj-id="getBaseId()" :edit-open="true"></base-image>
      </t-form-item>
      <t-row>
        <t-col :span="11">
          <t-space :size="10">
            <t-button @click="onCurChanged(2)" theme="primary" variant="base">上一步</t-button>
            <t-button theme="primary" @click="onSubmit3">下一步</t-button>
          </t-space>
        </t-col>
        <t-col :span="1" class="operation-container">
          <t-button variant="outline" @click="close">返回</t-button>
        </t-col>
      </t-row>
    </t-form>
    <!-- 宣传品 -->
    <t-form v-else-if="activeForm === 4" ref="form" :key="activeForm" :data="formData4" class="step-form"
      labelAlign="top" :rules="rules4" labelWidth="140px">
      <t-tag theme="danger" variant="light">列出科普站为公众提供的交通运输科普宣传品清单（限 5 种以内，附样品一套）:</t-tag>
      <t-form-item :show-error-message="false" name="imageList">
        <base-publicity ref="base-publicity" :obj-id="getBaseId()" v-model="formData4.publicityList"
          :editOpen="true"></base-publicity>
      </t-form-item>
      <t-row>
        <t-col :span="11">
          <t-space :size="10">
            <t-button @click="onCurChanged(3)" theme="primary" variant="base">上一步</t-button>
            <t-button theme="primary" @click="onSubmit4">下一步</t-button>
          </t-space>
        </t-col>
        <t-col :span="1" class="operation-container">
          <t-button variant="outline" @click="close">返回</t-button>
        </t-col>
      </t-row>
    </t-form>
    <!-- 科普解说词信息 -->
    <t-form v-else-if="activeForm === 5" ref="form" :key="activeForm" class="step-form" labelAlign="top"
      :data="formData5" :rules="rules5" labelWidth="140px">
      <t-tag theme="danger" variant="light">基地交通运输科普解说词一套（不超过2000字）</t-tag>
      <t-form-item name="commentary">
        <tiny-mce-editor :key="activeForm" :height="650" :maxlength="2000" :textLength.sync="lengthLimitObj.content"
          v-model="formData5.commentary"></tiny-mce-editor>
      </t-form-item>
      <t-row>
        <t-col :span="11">
          <t-space :size="10">
            <t-button @click="onCurChanged(4)" theme="primary" variant="base">上一步</t-button>
            <t-button theme="primary" @click="onSubmit5">下一步</t-button>
          </t-space>
        </t-col>
        <t-col :span="1" class="operation-container">
          <t-button variant="outline" @click="close">返回</t-button>
        </t-col>
      </t-row>
    </t-form>
    <!-- 嘉奖情况 -->
    <t-form v-else-if="activeForm === 6" ref="form" :key="activeForm" class="step-form" labelAlign="top"
      :data="formData6" labelWidth="140px" :rules="rules6">
      <t-tag theme="danger" variant="light">获厅局级及以上奖励情况（如有，提供相关证明，并在每张证书下面做 50 字以内的简要介绍）</t-tag>
      <t-form-item requiredMark name="reward">
        <base-reward ref="base-reward" :obj-id="getBaseId()" v-model="formData6.reward" :editOpen="true"></base-reward>
      </t-form-item>
      <t-row>
        <t-col :span="11">
          <t-space :size="10">
            <t-button @click="onCurChanged(5)" theme="primary" variant="base">上一步</t-button>
            <t-button theme="primary" @click="onSubmit6">下一步</t-button>
          </t-space>
        </t-col>
        <t-col :span="1" class="operation-container">
          <t-button variant="outline" @click="close">返回</t-button>
        </t-col>
      </t-row>
    </t-form>
    <!-- 典型活动 -->
    <t-form v-else-if="activeForm === 7" ref="form" :key="activeForm" class="step-form" labelAlign="top"
      :data="formData7" labelWidth="140px" :rules="rules7">
      <t-tag theme="danger" variant="light">列出近两年来科普站交通运输科普典型活动清单（限 10 个以内），同时提交开展的典型科普活动现场视频（时长 5
        分钟以内，大小不能超过1GB）</t-tag>
      <t-form-item :show-error-message="false" name="activity">
        <base-activity ref="base-activity" :obj-id="getBaseId()" v-model="formData7.activity"
          :editOpen="true"></base-activity>
      </t-form-item>
      <t-row>
        <t-col :span="11">
          <t-space :size="10">
            <t-button @click="onCurChanged(6)" theme="primary" variant="base">上一步</t-button>
            <t-button theme="primary" @click="onSubmit7">下一步</t-button>
          </t-space>
        </t-col>
        <t-col :span="1" class="operation-container">
          <t-button variant="outline" @click="close">返回</t-button>
        </t-col>
      </t-row>
    </t-form>
    <!-- 附件信息 -->
    <div class="step-form" v-else-if="activeForm === 8">
      <t-row>
        <t-col :span="12">
          <t-table row-key="id" :columns="projectFileColumns" :data="projectFileData2">
            <template #id="{ row, rowIndex }">
              {{ rowIndex + 1 }}
            </template>
            <template #op="{ row }">
              <file-upload tips="限制pdf" accept="application/pdf" v-model="row.fileIds" :moduleKey="row.moduleKey"
                :fileList="row.fileLists" :multiple="true">
                <t-button variant="outline">
                  <t-icon name="cloud-upload" slot="icon" />
                  点击上传
                </t-button>
              </file-upload>
            </template>
            <template #c1="{ row }">
              <a v-if="row.c3" class="t-button-link" :href="`${file_domain}/${row.c3}`" target="_blank">{{ row.c1 }}</a>
              <div v-else>{{ row.c1 }}</div>
            </template>
          </t-table>
        </t-col>
      </t-row>
      <t-row>
        <t-col :span="11">
          <t-space :size="10">
            <t-button @click="onCurChanged(6)" theme="primary" variant="base">上一步</t-button>
            <t-button theme="primary" :loading="submitLoading" @click="onSubmit8(1)">{{ submitLoading ? '提交中...' : '暂存'
              }}
            </t-button>
            <t-tooltip content="提交后不可再编辑会进入审批流程"
              v-if="this.formData0.baseStatus == 1 || this.formData0.baseStatus == 4">
              <t-button :loading="submitLoading" theme="primary" @click="onSubmit8(2)">
                {{ submitLoading ? '提交中...' : '提交到单位管理员' }}
              </t-button>
            </t-tooltip>
          </t-space>
        </t-col>
        <t-col :span="1" class="operation-container">
          <t-button variant="outline" @click="close">返回</t-button>
        </t-col>
      </t-row>
    </div>
  </div>
</template>

<script>
import TinyMceEditor from '@/components/TinyMceEditor/index.vue';
import fileUpload from '@/components/FileUpload/index.vue';
import { getFiles } from '@/api/common';
import BaseMember from './components/base-member.vue';
import BaseImage from './components/base-image.vue';
import BaseActivity from './components/base-activity.vue';
import BaseReward from './components/base-reward.vue';
import BasePublicity from './components/base-publicity.vue';

export default {
  name: 'base-apply',
  dicts: ['base_type', 'channel_type', 'worker_type', 'education', 'prof_tit'],
  components: {
    TinyMceEditor,
    fileUpload,
    BaseActivity,
    BaseReward,
    BasePublicity,
    BaseMember,
    BaseImage,
  },
  data () {
    return {
      visible: false,
      submitLoading: false,
      applyLoading: false,
      stepList: [
        {
          id: 'baseId',
          title: '基本信息',
          require: true,
        },
        {
          id: 'surveyId',
          title: '总体概况',
          require: true,
        },
        {
          id: 'contentId',
          title: '内容体系',
          require: true,
        },
        {
          id: 'pictureId',
          title: '特色照片',
          require: true,
        },
        {
          id: 'publicityId',
          title: '宣传品',
          require: true,
        },
        {
          id: 'commentaryId',
          title: '科普说词',
          require: true,
        },
        {
          id: 'rewardId',
          title: '嘉奖情况',
          require: true,
        },
        {
          id: 'activityId',
          title: '典型活动',
          require: false,
        },
        {
          id: 'fileId',
          title: '附件信息',
          require: false,
        },
      ],
      projectFileData: [
        {
          id: 1,
          c1: '评估报告',
          c2: '是',
          moduleKey: 'kpzhTSZP',
          fileIds: [],
          fileLists: [],
        },
        {
          id: 2,
          c1: '书面材料',
          c2: '是',
          moduleKey: 'smcl',
          fileIds: [],
          fileLists: [],
        },
      ],
      projectFileData2: [
        {
          id: 1,
          c1: '盖章后的申报书',
          c2: '否',
          moduleKey: 'kpzhsbs',
          fileIds: [],
          fileLists: [],
        },
      ],
      projectFileColumns: [
        {
          colKey: "id",
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: "c1",
          title: "附件名称",
          align: "center",
        },

        {
          colKey: "c2",
          title: "是否必需",
          align: "center",
        },
        {
          colKey: "op",
          title: "操作",
          align: "left",
        },
      ],
      lengthLimitObj: {
        survey: 0,
        surveyMax: 1000,
        content: 0,
        contentMax: 2000,
      },
      userDeptName: this.$store.state.user.deptName,
      taskId: undefined,
      activeForm: 0,
      formData0: {
        name: undefined,
        address: undefined,
        communicateAddress: undefined,
        postCode: undefined,
        legalPerson: undefined,
        linkerPerson: undefined,
        mobilePhone: undefined,
        fixedPhone: undefined,
        fax: undefined,
        email: undefined,
        baseType: undefined,
        workPlan: undefined,
        indoorVenues: undefined,
        outdoorVenues: undefined,
        lectureHall: undefined,
        openDays: undefined,
        receptionPerson: undefined,
        popularScienceWorkers: [],
        popularScienceFunding: {
          governmentInvest: undefined,
          socialSponsorship: undefined,
          unitSelf: undefined,
          other: undefined,
        },
        popularScienceBaseChannel: {
          webSite: 0,
          web: 0,
          webo: 0,
          weChat: 0,
          otherr: 0,
          url: undefined,
          otherClientName: undefined,
        },
        approveStatus: 1,
      },
      rules0: {
        name: [{ required: true, message: '申报科普站名称不能为空', trigger: 'blur' }],
        address: [{ required: true, message: '科普站地址不能为空' }],
        communicateAddress: [{ required: true, message: '通讯地址不能为空' }],
        postCode: [{ required: true, message: '邮编不能为空' }],
        legalPerson: [{ required: true, message: '法定代表人不能为空' }],
        linkerPerson: [{ required: true, message: '联系人不能为空' }],
        mobilePhone: [
          {
            required: true,
            message: '基本信息移动电话不能为空',
          },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '基本信息移动电话请输入正确的手机号码',
          },
        ],
        fixedPhone: [{ required: true, message: '固定电话不能为空' }],
        fax: [{ required: true, message: '传真不能为空' }],
        email: [
          {
            required: true,
            message: '基本信息公共邮箱不能为空',
          },
          { email: { ignore_max_length: true }, message: '基本信息请输入正确的公共邮箱地址' },
        ],
        baseType: [{ required: true, message: '基地类型不能为空' }],
        workPlan: [{ required: true, message: '交通运输科普工作管理制度、规划或计划不能为空' }],
        indoorVenues: [{ required: true, message: '室内场馆面积不能为空' }],
        outdoorVenues: [{ required: true, message: '室外场馆面积不能为空' }],
        lectureHall: [{ required: true, message: '影视报告厅面积不能为空' }],
        openDays: [{ required: true, message: '每年对外开放时间不能为空' }],
        receptionPerson: [{ required: true, message: '每年接待公众不能为空' }],
        popularScienceWorkers: [{ validator: (val) => val.length > 0, message: '科普工作人员不能为空', type: 'error' }],
        'popularScienceFunding.governmentInvest': [{ required: true, message: '政府投资不能为空' }],
        'popularScienceFunding.socialSponsorship': [{ required: true, message: '社会赞助不能为空' }],
        'popularScienceFunding.unitSelf': [{ required: true, message: '单位自筹不能为空' }],
        'popularScienceFunding.other': [{ required: true, message: '其他不能为空' }],
        // 'popularScienceBaseChannel.channelType': [{ required: false, message: '渠道类型能为空' }],
        // 'popularScienceBaseChannel.url': [{ required: true, message: '网址不能为空' }],
        // 'popularScienceBaseChannel.otherClientName': [{ required: true, message: '基地对外宣传渠道名称不能为空' }],
      },
      selectedMemberRowKeys: [-1],
      formData1: {
        survey: '',
      },
      rules1: {
        survey: [
          {
            required: true,
            message: '基地总体概况不能为空',
          },
        ],
      },
      formData2: {},
      rules2: {
        content: [
          {
            required: true,
            message: '交通运输科普展示内容体系不能为空',
          },
        ],
      },

      formData3: {
        imageList: [],
      },
      rules3: {
        imageList: [
          { required: true, validator: (val) => val && val.length, message: '特色照片不能为空', type: 'error' },
        ],
      },
      formData4: {
        publicityList: [],
      },
      rules4: {
        publicityList: [
          { required: true, validator: (val) => val && val.length, message: '宣传品清单不能为空', type: 'error' },
        ],
      },
      formData5: {
        commentary: '',
      },
      rules5: {
        commentary: [
          {
            required: true,
            message: '解说词不能为空',
          },
        ],
      },
      formData6: {
        reward: [],
      },
      rules6: {
        reward: [{ required: true, validator: (val) => val && val.length, message: '嘉奖情况不能为空', type: 'error' }],
      },
      formData7: {
        activity: [],
      },
      rules7: {
        activity: [
          { required: true, validator: (val) => val && val.length, message: '典型活动不能为空', type: 'error' },
        ],
      },
    };
  },
  watch: {
    activeForm: {
      immediate: true,
      handler (val) {
        const targetEle = document.getElementById('main');
        if (targetEle) {
          const { pos, top } = targetEle.style;
          targetEle.style.position = 'relative';
          targetEle.style.top = '-100px';
          targetEle.scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'nearest' });
          targetEle.style.top = top;
          targetEle.style.position = pos;
        }
      },
    },
  },
  async created () {
    const taskId = this.$route.params && this.$route.params.taskId;
    if (!taskId) {
      this.$message.error('任务id丢失返回我的科普基地');
      this.$router.push('/kpzh/science-base/base-my');
    }
    this.taskId = taskId;
    const activeForm = Number(sessionStorage.getItem(`${this.taskId}-kpzh-science-base-activeForm`)) || 0;
    this.onCurChanged(activeForm, 0);

  },
  methods: {

    getBaseId () {
      return sessionStorage.getItem(`${this.taskId}-kpzh-science-base-baseId`);
    },
    async onCurChanged (cur) {
      const numCur = Number(cur);
      if (numCur === 1) {
        if (!sessionStorage.getItem(`${this.taskId}-kpzh-science-base-baseId`)) {
          this.$message.error('基本信息还未提交');
          return false;
        }
      }
      this.applyLoading = true;
      if (Number(cur) === 0) {
        if (sessionStorage.getItem(`${this.taskId}-kpzh-science-base-baseId`)) {
          const baseId = Number(sessionStorage.getItem(`${this.taskId}-kpzh-science-base-baseId`));
          this.$api.kpzh.base
            .get(baseId)
            .then((response) => {
              Object.assign(this.formData0, response.data);
              this.activeForm = cur;
              sessionStorage.setItem(`${this.taskId}-activeForm`, cur);
              console.log(this.formData0.id);
              getFiles(this.formData0.id).then((response) => {
                console.log(response);
                this.projectFileData.forEach((fileData) => {
                  if (fileData.id === 2) {
                    const fileLists = []
                    response.data.forEach((item) => {
                      fileLists.push({
                        name: item.fileName,
                        url: item.fullFilePath,
                        id: item.id,
                        filePath: item.filePath,
                      });
                    });
                    fileData.fileLists = fileLists
                  }
                });

              });
              this.applyLoading = false;
            })
            .catch((e) => {
              this.applyLoading = false;
              this.$message.error(e.toString());
            });
        } else {
          this.activeForm = cur;
          sessionStorage.setItem(`${this.taskId}-activeForm`, cur);
          this.applyLoading = false;
        }
      } else if (Number(cur) === 1) {
        if (sessionStorage.getItem(`${this.taskId}-kpzh-science-base-baseId`)) {
          const baseId = Number(sessionStorage.getItem(`${this.taskId}-kpzh-science-base-baseId`));
          this.$api.kpzh.base
            .surveyGetBy(baseId)
            .then((response) => {
              Object.assign(this.formData1, response.data);
              this.activeForm = cur;
              sessionStorage.setItem(`${this.taskId}-activeForm`, cur);
              this.applyLoading = false;
            })
            .catch((e) => {
              this.applyLoading = false;
              this.$message.error(e.toString());
            });
        } else {
          this.activeForm = cur;
          sessionStorage.setItem(`${this.taskId}-activeForm`, cur);
          this.applyLoading = false;
        }
      } else if (Number(cur) === 2) {
        if (sessionStorage.getItem(`${this.taskId}-kpzh-science-base-baseId`)) {
          const baseId = Number(sessionStorage.getItem(`${this.taskId}-kpzh-science-base-baseId`));
          this.$api.kpzh.base
            .contentGetBy(baseId)
            .then((response) => {
              Object.assign(this.formData2, response.data);
              this.activeForm = cur;
              sessionStorage.setItem(`${this.taskId}-activeForm`, cur);
              this.applyLoading = false;
            })
            .catch((e) => {
              this.applyLoading = false;
              this.$message.error(e.toString());
            });
        } else {
          this.activeForm = cur;
          sessionStorage.setItem(`${this.taskId}-activeForm`, cur);
          this.applyLoading = false;
        }
      } else if (Number(cur) === 3) {
        if (sessionStorage.getItem(`${this.taskId}-kpzh-science-base-baseId`)) {
          const baseId = Number(sessionStorage.getItem(`${this.taskId}-kpzh-science-base-baseId`));
          this.$api.kpzh.base
            .pictureList(baseId)
            .then((response) => {
              Object.assign(this.formData3.imageList, response.data);
              this.activeForm = cur;
              sessionStorage.setItem(`${this.taskId}-activeForm`, cur);
              this.applyLoading = false;
            })
            .catch((e) => {
              this.applyLoading = false;
              this.$message.error(e.toString());
            });
        } else {
          this.activeForm = cur;
          sessionStorage.setItem(`${this.taskId}-activeForm`, cur);
          this.applyLoading = false;
        }
      } else if (Number(cur) === 4) {
        if (sessionStorage.getItem(`${this.taskId}-kpzh-science-base-baseId`)) {
          const baseId = Number(sessionStorage.getItem(`${this.taskId}-kpzh-science-base-baseId`));
          this.$api.kpzh.base
            .publicityList(baseId)
            .then((response) => {
              Object.assign(this.formData4.publicityList, response.data);
              this.activeForm = cur;
              sessionStorage.setItem(`${this.taskId}-activeForm`, cur);
              this.applyLoading = false;
            })
            .catch((e) => {
              this.$message.error(e.toString());
              this.applyLoading = false;
            });
        } else {
          this.activeForm = cur;
          sessionStorage.setItem(`${this.taskId}-activeForm`, cur);
          this.applyLoading = false;
        }
      } else if (Number(cur) === 5) {
        if (sessionStorage.getItem(`${this.taskId}-kpzh-science-base-baseId`)) {
          const baseId = Number(sessionStorage.getItem(`${this.taskId}-kpzh-science-base-baseId`));
          this.$api.kpzh.base
            .commentaryBy(baseId)
            .then((response) => {
              Object.assign(this.formData5, response.data);
              this.activeForm = cur;
              sessionStorage.setItem(`${this.taskId}-activeForm`, cur);
              this.applyLoading = false;
            })
            .catch((e) => {
              this.$message.error(e.toString());
              this.applyLoading = false;
            });
        } else {
          this.activeForm = cur;
          sessionStorage.setItem(`${this.taskId}-activeForm`, cur);
          this.applyLoading = false;
        }
      } else if (Number(cur) === 6) {
        if (sessionStorage.getItem(`${this.taskId}-kpzh-science-base-baseId`)) {
          const baseId = Number(sessionStorage.getItem(`${this.taskId}-kpzh-science-base-baseId`));
          this.$api.kpzh.base
            .rewardList(baseId)
            .then((response) => {
              Object.assign(this.formData6.reward, response.data);
              this.activeForm = cur;
              sessionStorage.setItem(`${this.taskId}-activeForm`, cur);
              this.applyLoading = false;
            })
            .catch((e) => {
              this.$message.error(e.toString());
              this.applyLoading = false;
            });
        } else {
          this.activeForm = cur;
          sessionStorage.setItem(`${this.taskId}-activeForm`, cur);
          this.applyLoading = false;
        }
      } else if (Number(cur) === 7) {
        if (sessionStorage.getItem(`${this.taskId}-kpzh-science-base-baseId`)) {
          const baseId = Number(sessionStorage.getItem(`${this.taskId}-kpzh-science-base-baseId`));
          this.$api.kpzh.base
            .activityList(baseId)
            .then((response) => {
              Object.assign(this.formData7.activity, response.data);
              this.activeForm = cur;
              sessionStorage.setItem(`${this.taskId}-activeForm`, cur);
              this.applyLoading = false;
            })
            .catch((e) => {
              this.$message.error(e.toString());
              this.applyLoading = false;
            });
        } else {
          this.activeForm = cur;
          sessionStorage.setItem(`${this.taskId}-activeForm`, cur);
          this.applyLoading = false;
        }
      } else if (Number(cur) === 8) {
        getFiles(sessionStorage.getItem(`${this.taskId}-kpzh-science-base-baseId`)).then((res) => {
          const files = {}
          res.data.forEach((item) => {
            if (!files[item.moduleKey]) {
              files[item.moduleKey] = []
            }
            files[item.moduleKey].push({
              name: item.fileName,
              url: item.fullFilePath,
              id: item.id,
              filePath: item.filePath
            })
          })
          const fileLists = []
          this.projectFileData2.forEach((val, index) => {
            this.projectFileData2[index].fileLists = files[val.moduleKey] || [];
            this.projectFileData2[index].fileIds = files[val.moduleKey]?.map(val => val.id) || [];
            fileLists.push(...this.projectFileData2[index].fileIds)
          })
          if (fileLists.length > 0) {
            sessionStorage.setItem(`${this.taskId}-fileId`, res.data.length)
          }
          this.activeForm = cur;
          sessionStorage.setItem(`${this.taskId}-activeForm`, cur);
          this.applyLoading = false;
        }).catch((e) => {
          this.applyLoading = false;
          this.$message.error(e.toString());
        });
      } else {
        this.activeForm = cur;
        sessionStorage.setItem(`${this.taskId}-kpzh-science-base-activeForm`, cur);
        this.applyLoading = false;
      }
    },
    isSubmit (name) {
      return sessionStorage.getItem(`${this.taskId}-kpzh-science-base-${name}`) ? '已提交' : '未提交';
    },
    onSubmit0 () {
      this.$refs.form.validate().then((validateResult) => {
        if (validateResult === true) {
          // this.formData0.baseStatus = "0"
          let sysAttMainIds = [];
          this.projectFileData.forEach((fileData) => {
            if (fileData.id === 2) {
              sysAttMainIds = [...fileData.fileIds];
            }
          });
          if (!sessionStorage.getItem(`${this.taskId}-kpzh-science-base-baseId`)) {
            this.$api.kpzh.base
              .add({
                ...this.formData0,
                sysAttMainVo: {
                  sysAttMainIds,
                },
              })
              .then((response) => {
                sessionStorage.setItem(`${this.taskId}-kpzh-science-base-baseId`, response.data.id);
                this.$message.success('提交成功');
                this.onCurChanged(1);
              })
              .catch((e) => {
                this.$message.error(e.toString());
              });
          } else {
            this.$api.kpzh.base
              .update({
                ...this.formData0,
                sysAttMainVo: {
                  sysAttMainIds,
                },
              })
              .then((response) => {
                this.$message.success('修改成功');
                this.onCurChanged(1);
              })
              .catch((e) => {
                this.$message.error(e.toString());
              });
          }
        } else {
          const firstError = Object.values(validateResult)[0]?.[0]?.message;
          this.$message.error(firstError);
        }
      });
    },
    onSubmit1 () {
      this.$refs.form.validate().then((validateResult) => {
        if (validateResult === true) {
          if (this.lengthLimitObj.survey > this.lengthLimitObj.surveyMax) {
            this.$message.error(
              `基地总体概况：当前字数：${this.lengthLimitObj.survey}，限制字数：${this.lengthLimitObj.surveyMax}`,
            );
            return false;
          }
          this.formData1.baseId = Number(sessionStorage.getItem(`${this.taskId}-kpzh-science-base-baseId`));
          if (!sessionStorage.getItem(`${this.taskId}-kpzh-science-base-surveyId`)) {
            this.$api.kpzh.base
              .surveyAdd(this.formData1)
              .then((response) => {
                sessionStorage.setItem(`${this.taskId}-kpzh-science-base-surveyId`, response.data.id);
                this.$message.success('提交成功');
                this.onCurChanged(2);
              })
              .catch((e) => {
                this.$message.error(e.toString());
              });
          } else {
            this.$api.kpzh.base
              .surveyUpdate(this.formData1)
              .then((response) => {
                this.$message.success('修改成功');
                this.onCurChanged(2);
              })
              .catch((e) => {
                this.$message.error(e.toString());
              });
          }
        } else {
          const firstError = Object.values(validateResult)[0]?.[0]?.message;
          this.$message.error(firstError);
        }
      });
    },
    onSubmit2 () {
      this.$refs.form.validate().then((validateResult) => {
        if (validateResult === true) {
          if (this.lengthLimitObj.content > this.lengthLimitObj.contentMax) {
            this.$message.error(
              `交通运输科普展示内容体系：当前字数：${this.lengthLimitObj.content}，限制字数：${this.lengthLimitObj.contentMax}`,
            );
            return false;
          }
          this.formData2.baseId = Number(sessionStorage.getItem(`${this.taskId}-kpzh-science-base-baseId`));
          if (!sessionStorage.getItem(`${this.taskId}-kpzh-science-base-contentId`)) {
            this.$api.kpzh.base
              .contentAdd(this.formData2)
              .then((response) => {
                sessionStorage.setItem(`${this.taskId}-kpzh-science-base-contentId`, response.data.id);
                this.$message.success('提交成功');
                this.onCurChanged(3);
              })
              .catch((e) => {
                this.$message.error(e.toString());
              });
          } else {
            this.$api.kpzh.base
              .contentUpdate(this.formData2)
              .then((response) => {
                this.$message.success('修改成功');
                this.onCurChanged(3);
              })
              .catch((e) => {
                this.$message.error(e.toString());
              });
          }
        } else {
          const firstError = Object.values(validateResult)[0]?.[0]?.message;
          this.$message.error(firstError);
        }
      });
    },
    onSubmit3 () {
      this.$refs.form.validate().then((validateResult) => {
        if (validateResult === true) {
          const isValidate = this.$refs['base-image'].checkData();
          if (!isValidate) {
            return false;
          }
          this.$api.kpzh.base
            .picAddList(this.formData3.imageList)
            .then((response) => {
              sessionStorage.setItem(`${this.taskId}-kpzh-science-base-pictureId`, '1');
              this.$message.success('提交成功');
              this.onCurChanged(4);
            })
            .catch((e) => {
              this.$message.error(e.toString());
            });
        } else {
          const firstError = Object.values(validateResult)[0]?.[0]?.message;
          this.$message.error(firstError);
        }
      });
    },
    onSubmit4 () {
      this.$refs.form.validate().then((validateResult) => {
        if (validateResult === true) {
          const isValidate = this.$refs['base-publicity'].checkData();
          if (!isValidate) {
            return false;
          }
          this.$api.kpzh.base
            .publicityAddList(this.formData4.publicityList)
            .then((response) => {
              sessionStorage.setItem(`${this.taskId}-kpzh-science-base-publicityId`, '1');
              this.$message.success('提交成功');
              this.onCurChanged(5);
            })
            .catch((e) => {
              this.$message.error(e.toString());
            });
        } else {
          const firstError = Object.values(validateResult)[0]?.[0]?.message;
          this.$message.error(firstError);
        }
      });
    },
    onSubmit5 () {
      this.$refs.form.validate().then((validateResult) => {
        if (validateResult === true) {
          if (this.lengthLimitObj.content > this.lengthLimitObj.contentMax) {
            this.$message.error(
              `科普解说词信息：当前字数：${this.lengthLimitObj.content}，限制字数：${this.lengthLimitObj.contentMax}`,
            );
            return false;
          }
          this.formData5.baseId = Number(sessionStorage.getItem(`${this.taskId}-kpzh-science-base-baseId`));
          if (!sessionStorage.getItem(`${this.taskId}-kpzh-science-base-commentaryId`)) {
            this.$api.kpzh.base
              .commentaryAdd(this.formData5)
              .then((response) => {
                sessionStorage.setItem(`${this.taskId}-kpzh-science-base-commentaryId`, response.data.id);
                this.$message.success('提交成功');
                this.onCurChanged(6);
              })
              .catch((e) => {
                this.$message.error(e.toString());
              });
          } else {
            // delete this.formData5.baseId
            this.formData5.id = sessionStorage.getItem(`${this.taskId}-kpzh-science-base-commentaryId`);
            this.$api.kpzh.base
              .commentaryEdit(this.formData5)
              .then((response) => {
                this.$message.success('修改成功');
                this.onCurChanged(6);
              })
              .catch((e) => {
                this.$message.error(e.toString());
              });
          }
        } else {
          const firstError = Object.values(validateResult)[0]?.[0]?.message;
          this.$message.error(firstError);
        }
      });
    },
    onSubmit6 () {
      this.$refs.form.validate().then((validateResult) => {
        if (validateResult === true) {
          const isValidate = this.$refs['base-reward'].checkData();
          if (!isValidate) {
            return false;
          }
          this.$api.kpzh.base
            .rewardAddList(this.formData6.reward)
            .then((response) => {
              sessionStorage.setItem(`${this.taskId}-kpzh-science-base-rewardId`, '1');
              this.$message.success('提交成功');
              this.onCurChanged(7);
            })
            .catch((e) => {
              this.$message.error(e.toString());
            });
        } else {
          const firstError = Object.values(validateResult)[0]?.[0]?.message;
          this.$message.error(firstError);
        }
      });
    },
    onSubmit7 () {
      this.$refs.form.validate().then((validateResult) => {
        if (validateResult === true) {
          const isValidate = this.$refs['base-activity'].checkData();
          if (!isValidate) {
            return false;
          }
          this.$api.kpzh.base
            .activityAddList(this.formData7.activity)
            .then((response) => {
              sessionStorage.setItem(`${this.taskId}-kpzh-science-base-activityId`, '1');
              this.$message.success('提交成功');
              this.onCurChanged(8);
            })
            .catch((e) => {
              this.submitLoading = false;
              this.$message.error(e.toString());
            });
        } else {
          const firstError = Object.values(validateResult)[0]?.[0]?.message;
          this.$message.error(firstError);
        }
      });
    },
    onSubmit8 (type) {
      const sysAttMainIds = []
      this.projectFileData2.forEach(val => {
        sysAttMainIds.push(...val.fileIds)
      })
      if (type === 1) {
        this.submitLoading = true;

        this.$api.kpzh.base
          .edit({
            id: Number(sessionStorage.getItem(`${this.taskId}-kpzh-science-base-baseId`)),
            sysAttMainVo: {
              sysAttMainIds,
            }
          })
          .then((response) => {
            sessionStorage.setItem(`${this.taskId}-kpzh-science-base-fileId`, this.projectFileData2.length);
            this.submitLoading = false;
            this.$message.success('暂存成功');
            this.close();
          })
          .catch((e) => {
            this.submitLoading = false;
            this.$message.error(e.toString());
          });
      } else {
        console.log(this.$refs.form);

        // this.$refs.form.validate().then((validateResult) => {
        //   if (validateResult === true) {
        //     const checkResult = this.$refs['base-activity'].checkData();
        //     if (!checkResult) {
        //       return;
        //     }
        this.stepList.forEach((val) => {
          if (!sessionStorage.getItem(`${this.taskId}-kpzh-science-base-${val.id}`) && val.require) {
            this.$message.error(`${val.title}还未提交`);
            this.applyLoading = false;
            return false;
          }
        });
        this.submitLoading = true;
        this.$api.kpzh.base
          .submit({
            id: Number(sessionStorage.getItem(`${this.taskId}-kpzh-science-base-baseId`)),
            sysAttMainVo: {
              sysAttMainIds,
            }
          })
          .then((response) => {
            sessionStorage.setItem(`${this.taskId}-kpzh-science-base-fileId`, this.projectFileData2.length);
            this.submitLoading = false;
            this.$message.success('提交成功');
            this.close();
          })
          .catch((e) => {
            this.submitLoading = false;
            this.$message.error(e.toString());
          });
        // } else {
        //   const firstError = Object.values(validateResult)[0]?.[0]?.message;
        //   this.$message.error(firstError);
        // }
        //   });
      }
    },
    close () {
      this.$tab.closeOpenPage({ path: '/kpzh/science-base/base-my' });
    },
  },
};
</script>


<style lang="less" scoped>
.step-form {
  padding: 0 24px;
}

.t-row {
  margin-bottom: 14px;
}

.step-card {
  height: 100%;
  //margin-bottom: 14px;
  padding-bottom: 14px;
  //flex: 1;
}

// 删除
.tdesign-demo-image-viewer__ui-image {
  width: 160px;
  height: 160px;
  display: inline-flex;
  position: relative;
  justify-content: center;
  align-items: center;
  border-radius: var(--td-radius-small);
  overflow: hidden;
}

.tdesign-demo-image-viewer__ui-image--hover {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  left: 0;
  top: 0;
  opacity: 0;
  background-color: rgba(0, 0, 0, 0.6);
  color: var(--td-text-color-anti);
  line-height: 22px;
  transition: 0.2s;
}

.tdesign-demo-image-viewer__ui-image:hover .tdesign-demo-image-viewer__ui-image--hover {
  opacity: 1;
  cursor: pointer;
}

.tdesign-demo-image-viewer__ui-image--img {
  width: auto;
  height: auto;
  max-width: 100%;
  max-height: 100%;
  cursor: pointer;
  position: absolute;
}

.tdesign-demo-image-viewer__ui-image--footer {
  padding: 0 16px;
  height: 56px;
  width: 100%;
  line-height: 56px;
  font-size: 16px;
  position: absolute;
  bottom: 0;
  color: var(--td-text-color-anti);
  background-image: linear-gradient(0deg, rgba(0, 0, 0, 0.4) 0%, rgba(0, 0, 0, 0) 100%);
  display: flex;
  box-sizing: border-box;
}

.tdesign-demo-image-viewer__ui-image--title {
  flex: 1;
}

.tdesign-demo-popup__reference {
  margin-left: 16px;
}

.tdesign-demo-image-viewer__ui-image--icons .tdesign-demo-icon {
  cursor: pointer;
}

.tdesign-demo-image-viewer__base {
  width: 160px;
  height: 160px;
  margin: 10px;
  border: 4px solid var(--td-bg-color-secondarycontainer);
  border-radius: var(--td-radius-medium);
}
</style>
